<template>
  <el-card>
    <div slot="header">
      <h3>维护商品SKU信息(包装)</h3>
    </div>
    <div>
      <el-row type="flex" justify="end" align="middle">
        <el-button
          size="middle"
          type="text"
          :loading="exportLoading"
          @click="handleExportFile"
          >模板导出</el-button
        >
        <el-divider direction="vertical"></el-divider>
        <el-upload
          class="import-file"
          ref="bacthUpload"
          :action="`${uploadBaseURL}sysback/product/addSku/packageInfo/importAuditSkuPackageInfo?productUuid=${this.productUuid}`"
          accept=".xls, .xlsx"
          :before-upload="beforeFileUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
          :show-file-list="false"
        >
        <el-button size="middle" type="text" :loading="importBtnLoading"
          >模板导入</el-button
        >
        </el-upload>
        <el-divider direction="vertical"></el-divider>
        <el-button
          size="large"
          type="text"
          :loading="btnLoading.submit"
          @click="handleSubmitData"
          >保存</el-button
        >
      </el-row>
      <el-row class="item_wrap">
        <GeneralTable
          :loading="tableInfo.loading"
          :data-source="tableInfo.list"
          :columns="tableInfo.columns"
          @handleChangeInputNumber="handleChangeInputNumber"
        />
      </el-row>
    </div>
    <SelectUnitDialog
      :visible.sync="mainUnitVisible"
      @getUnitName="handleGetMainUnitName"
    />
    <!-- 选择产地弹框 -->
    <OriginalPlaceDialog
      :visible.sync="originalPlaceVisible"
      @getOriginalPlace="getOriginalPlaceFn"
    />
  </el-card>
</template>
<script>
import { ApiRequest, ApiRequestExportTable } from '@api/basePage';
/* components */
import GeneralTable from '@/pages/commodity/modules/components/generalTable';
import SelectUnitDialog from '@/pages/commodity/components/SelectUnitDialog';
import OriginalPlaceDialog from '@/components/common/dialog/originalPlaceDialog';
/* constants */
import { getTableColumnsFn } from '../../constants/skuToBePerfect/skuPackageInfo';
/* utils */
import { getSkuVolumnByCalculate } from '@/utils/getUtils';
import { isResponseSuccess, isResponseSuccessState } from '@/utils/bizUtils';
export default {
  components: {
    GeneralTable,
    SelectUnitDialog,
    OriginalPlaceDialog
  },
  data () {
    return {
      exportLoading: false,
      importBtnLoading: false,
      tableInfo: {
        list: [], // 表格数据
        columns: [], // 表格columns
        loading: false // 表格加载loading
      },
      btnLoading: {
        submit: false // 提交按钮loading
      },
      originalPlaceVisible: false,
      productUuid: '',
      mainUnitVisible: false, // 选择主计量单位弹框开关状态
      storageCurrentRowData: {}, // 存储当前操作row，用于主计量单位的赋值
      apiObj: {
        getPackageInfoListByProductUuid: { // 查询包装信息
          url: '/sysback/product/addSku/packageInfo/getPackageInfoListByProductUuid',
          type: 'post'
        },
        saveSpuAddSkuPackage: { // 保存包装信息
          url: '/sysback/product/addSku/packageInfo/saveSpuAddSkuPackage',
          type: 'post'
        },
        exportApi: { // 导出包装信息
          url: '/sysback/product/addSku/packageInfo/exportAuditSkuPackageInfo',
          type: 'post'
        }
      }
    }
  },
  created () {
    this.productUuid = this.$route.query.productUuid;
    this.initTableDataFn();
  },
  mounted () {
    this.tableInfo.columns = _.cloneDeep(
      getTableColumnsFn({
        handleChooseMainUnit: this.handleChooseMainUnit,
        handleChooseOriginalPlace: this.handleChooseOriginalPlace
      })
    );
  },
  methods: {
    // 获取产地信息方法
    getOriginalPlaceFn (data) {
      const { producingAreaName, producingAreaCode } = data;
      const { index } = this.storageCurrentRowData;
      this.tableInfo.list[index].producingAreaName = producingAreaName;
      this.tableInfo.list[index].producingAreaCode = producingAreaCode;
    },
    // 选择产地事件
    handleChooseOriginalPlace ({ index }) {
      this.storageCurrentRowData.index = index;
      this.originalPlaceVisible = true;
    },
    // 初始化表格数据
    async initTableDataFn () {
      const data = {};
      const { url, type } = this.apiObj.getPackageInfoListByProductUuid;
      const apiUrl = `${url}?productUuid=${this.productUuid}`;
      try {
        this.tableInfo.loading = true;
        const res = await ApiRequest(apiUrl, type, data, false);
        this.tableInfo.loading = false;
        if (isResponseSuccess(res)) {
          this.tableInfo.list = this.getTableInfoListFn(res.retData);
        }
      } catch (err) {
        this.tableInfo.loading = false;
      }
    },
    // 获取重组表格数据
    getTableInfoListFn (source) {
      const { main, packageList } = source;
      return packageList.reduce((value, row) => {
        row.singleVolume = getSkuVolumnByCalculate({ type: { start: 'single' }, row });
        row.oneVolume = getSkuVolumnByCalculate({ type: { start: 'one' }, row });
        row.twoVolume = getSkuVolumnByCalculate({ type: { start: 'two' }, row });
        row.threeVolume = getSkuVolumnByCalculate({ type: { start: 'three' }, row });
        value.push({
          ...main,
          ...row
        });
        return value;
      }, []);
    },
    // 选择主计量单位
    handleChooseMainUnit (data) {
      this.storageCurrentRowData = data;
      this.mainUnitVisible = true;
    },
    handleGetMainUnitName (unitName) {
      const { type, index } = this.storageCurrentRowData;
      this.tableInfo.list[index][type] = unitName;
    },
    // 计算体积
    handleChangeInputNumber (data) {
      const { row, columnName } = data;
      const typeSplit = _.lowerCase(columnName).split(' '); // 转换字符串string以空格分开单词，并转换为小写,并通过split切割成对应的数组
      const type = typeSplit[0]; // 只取第一项，分别对应 single one two three四种情况
      row[`${type}Volume`] = getSkuVolumnByCalculate({ type: { start: type }, row });
    },
    beforeFileUpload (file) {
      this.tableInfo.loading = true;
      this.importBtnLoading = true;
    },
    uploadSuccess (res) {
      this.tableInfo.loading = false;
      this.importBtnLoading = false;
      if (isResponseSuccess(res)) {
        this.tableInfo.list = [];
        this.tableInfo.list = this.getTableInfoListFn(res.retData);
      } else {
        this.$message.error(res.retMessage || '模板导入异常');
      }
    },
    uploadError (file) {
      this.tableLoading = false;
      this.importBtnLoading = false;
      this.$message.error('模板导入异常');
    },
    // 模板导出
    handleExportFile () {
      if (this.tableInfo.list.length === 0) {
        return this.$Message.warning('无准入sku信息');
      }
      this.exportLoading = true;
      ApiRequestExportTable(
        this.apiObj.exportApi.url,
        this.apiObj.exportApi.type,
        { 'productUuid': this.productUuid },
        false
      )
        .then((res) => {
          this.exportLoading = false;
          const blob = new Blob([res], {
            type: 'application/octet-stream'
          });
          var link = document.createElement('a');
          link.href = window.URL.createObjectURL(blob);
          link.download = '维护商品SKU信息(包装).xlsx';
          link.click();
          window.URL.revokeObjectURL(blob); // 释放掉blob对象
        })
        .catch(() => {
          this.exportLoading = false;
        });
    },
    // 提交数据
    async handleSubmitData () {
      const data = {
        productUuid: this.productUuid,
        packageList: this.tableInfo.list
      }
      const { url, type } = this.apiObj.saveSpuAddSkuPackage;
      try {
        this.btnLoading.submit = true;
        const res = await ApiRequest(url, type, data, false);
        this.btnLoading.submit = false;
        if (isResponseSuccessState(res.retStatus)) {
          this.$message.success('保存成功');
          this.$router.go(-1)
        }
      } catch (err) {
        this.btnLoading.submit = false;
      }
    },
  }
}
</script>
<style lang="less" scoped>
.item_wrap {
  margin: 10px 0px;
}
.btn-wrap {
  float: right;
  .import-file {
    display: inline;
  }
}
/deep/ .el-card__header {
  padding: 10px 20px;
}
</style>
